<?php
namespace  common\components\services\customer;
use common\components\helpers\Fun;
use common\models\datas\AccountRecord;
use common\models\datas\Customer;
use common\models\datas\CustomerBranchaccount;
use common\models\datas\Recharge;
use common\models\datas\ScholarshipFrozenLog;
use yii\base\Component;
use yii\helpers\ArrayHelper;
use zhtfrontend\models\datas\OrdersSquarePaymethod;

/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2016/4/27
 * Time: 14:42
 */
class Account extends Component
{

    /**
     *  会员资金增加
     */
    public static function CustomerAccountIncrease($option){
           $BAccount = CustomerBranchaccount::find()->where(['site_id'=>Fun::getSiteId(),'customer_id'=>$option['customer_id']])->one();
           $accounts = isset($option['account'])?(int)$option['account']: 0;
           $scholarship_available = isset($option['scholarship_available'])?(int)$option['scholarship_available']: 0;
           $deposit = isset($option['deposit'])?(int)$option['deposit']: 0;
           $orders_id = isset($option['orders_id'])?$option['orders_id']: 0;
           $note = isset($option['note'])?$option['note']: '';
           $state = isset($option['state'])?$option['state']: 0;
           $paymentList = OrdersSquarePaymethod::find()->where(['orders_id'=>$orders_id])->all();
           $pay_p = 0;
           $pay_code_field = '';
           if($paymentList != null){
              // $paycodearr = ArrayHelper::getColumn($paymentList,'pay_code');
               foreach ($paymentList as $pay_mode){
                   if($pay_mode == 'music_cash'){
                      if($accounts > $pay_mode->amount){
                          $pay_p = $pay_mode->amount;
                      }else{
                          $pay_p = $accounts;
                      }
                       $pay_code_field ='music_cash';
                   }
                   if($pay_mode == 'puzzle_cash'){
                      if($accounts > $pay_mode->amount){
                          $pay_p = $pay_mode->amount;
                      }else{
                          $pay_p = $accounts;
                      }
                       $pay_code_field ='puzzle_cash';
                   }
                   if($pay_mode == 'body_cash'){
                      if($accounts > $pay_mode->amount){
                          $pay_p = $pay_mode->amount;
                      }else{
                          $pay_p = $accounts;
                      }
                       $pay_code_field ='body_cash';
                   }
               }
           }
           $pay_account = $accounts - $pay_p;
            if($BAccount == null){
                $BAccount = new CustomerBranchaccount();
                $BAccount->customer_id = $option['customer_id'];
                $BAccount->site_id = Fun::getSiteId();
                $BAccount->cash = $pay_account;
                $BAccount->scholarship_available = $scholarship_available;
                if($pay_code_field != null){
                    $BAccount->$pay_code_field = $pay_p;
                }
                //$BAccount->deposit = $deposit;
                $BAccount->mode = $option['mode'];
                $BAccount->created_at = time();
                $BAccount->updated_at = time();
            }else{
                $BAccount->cash += $pay_account;
                $BAccount->scholarship_available += $scholarship_available;
                if($pay_code_field != null){
                    $BAccount->$pay_code_field = $pay_p;
                }
                //$BAccount->deposit += $deposit;
                $BAccount->updated_at = time();
            }
           if($BAccount->save(false)){
               $account = new AccountRecord();
               $account->customer_id = $option['customer_id'];
               $account->cash = $accounts+$scholarship_available;
               $account->state = $state;
               $account->order_id = $orders_id;
               $account->note = $note;
               $account->created_at = time();
               $account->site_id = Fun::getSiteId();
               $account->user_id = \Yii::$app->user->id;
               $account->pay_account = $accounts;
               $account->pay_scholarship = $scholarship_available;
               $account->deposit = $deposit;
               $account->save(false);
               return true;
           }
        return false;
    }

    /**
     *  会员资金减少
     */
    public static function CustomerAccountReduce($option){
        $CBAccount = CustomerBranchaccount::find()->where(['customer_id'=>$option['customer_id'],'site_id'=>Fun::getSiteId()])->one();

        $pay_account = isset($option['account'])?(float)$option['account']: 0;
        $scholarship_available = isset($option['scholarship_available'])?(float)$option['scholarship_available']: 0;
        $deposit = isset($option['deposit'])?(float)$option['deposit']: 0;
        $orders_id = isset($option['orders_id'])?$option['orders_id']: 0;
        $note = isset($option['note'])?$option['note']: '';
        $state = isset($option['state'])?$option['state']: 0;
        $CBAccount->cash -= $pay_account;
        $CBAccount->scholarship_available -= $scholarship_available;
        //$CBAccount->deposit -= $deposit;
        if($CBAccount->save(false)){
            $account = new AccountRecord();
            $account->customer_id = $CBAccount->customer_id;
            $account->site_id = $CBAccount->site_id;
            $account->cash = -($pay_account+$scholarship_available);
            $account->state = $state;
            $account->order_id = $orders_id;
            $account->note = $note;
            $account->created_at = time();
            $account->user_id = \Yii::$app->user->id;
            $account->pay_account = -$pay_account;
            $account->pay_scholarship = -$scholarship_available;
            $account->deposit = -$deposit;
            $account->save(false);
            return true;
        }
        return false;
    }

    //记录充值
    public static function addRecharge($customer_id,$money){
        $site_id = Fun::getSiteId();
        $frequency = Recharge::find()->where(['customer_id'=>$customer_id,'site_id'=>$site_id])->count();
        $rechageModel = new Recharge();
        $rechageModel->customer_id = $customer_id;
        $rechageModel->site_id = $site_id;
        $rechageModel->cash = $money;
        $rechageModel->surplus_cash = $money;
        $rechageModel->frequency = $frequency+1;
        $rechageModel->isuser_id = 0;
        $rechageModel->save(false);
    }

    //减少充值金额
    public static function reduceRecharge($customer_id,$money){
        $site_id = Fun::getSiteId();
        $all = Recharge::find()->where(['customer_id'=>$customer_id,'site_id'=>$site_id])->andWhere(['>','surplus_cash',0])->orderBy('frequency ASC')->all();
        foreach ($all as $val){
             $surplus_cash = $val->surplus_cash;
            if($surplus_cash >= $money && $money > 0){
                $val->surplus_cash =  $val->surplus_cash-$money;
                $val->save(false);
                break;
            }else{
                $val->surplus_cash =  0;
                $val->save(false);
            }
            $money -= $surplus_cash;
        }
    }

    /*
     * 微信端针对账户资金流动的记录操作
     */
    public static function  accountforWechatChange($customer, $max_amount, $options){
        $account_type = isset($options['account_type'])?$options['account_type']:0;//资金变动类型：卡激活，订单等
        $scholarship = isset($options['scholarship'])?$options['scholarship']:0;
        $cash = isset($options['cash'])?$options['cash']:0;
        $account = isset($options['account'])?$options['account']:0;
        $deposit = isset($options['deposit_money'])&&!empty($options['deposit_money'])?-$options['deposit_money']:0;//交保证金都是负数
        $site_id = Fun::getSiteId()?Fun::getSiteId():0;
        $account_record_data = [
            'customer_id' => $customer['id'],
            'site_id' => $site_id,
            'user_id' => $customer['id'],
            'created_at' => time(),
            'pay_cash' => $cash,
            'pay_pos' => 0,
            'pay_card' => 0,
            'pay_account' => $account,
            'pay_scholarship' => $scholarship,
            'state' => $account_type,
            'deposit' => $deposit,
        ];
        if($account_type == 6) {//卡激活奖学金
            $card_attr_id = isset($options['card_attr_id']) ? $options['card_attr_id'] : 0;
            $account_money['scholar_add_amount'] = $scholarship;
            $account_money['cash_add_amount'] = $cash;
            $spendscholarship = isset($options['spendscholarship'])?$options['spendscholarship']:0;
            Account::changeCustomerAccount($customer,$max_amount,$account_money,$account_type,$spendscholarship);
            $account_record_data['scholarship_rel_id'] = $card_attr_id;
            $account_record_data['cash'] = $account_record_data['pay_cash']+$account_record_data['pay_pos']+$account_record_data['pay_card']+$account_record_data['pay_scholarship']+$account_record_data['deposit'];
            $account_record_data['note'] = '卡激活奖学金';
            \Yii::$app->db->createCommand()->insert('{{%account_record}}', $account_record_data)->execute();
        }elseif($account_type == 5){//订单，此时的金额应该都是负值
            $account_money['scholar_add_amount'] = $scholarship>0 ? -$scholarship:0;
            $account_money['cash_add_amount'] = $cash>0 ? -$cash:0;
            $account_money['deposit'] = $deposit;
            $order_id = isset($options['order_id'])?$options['order_id'] : 0;//订单独有的
            Account::changeCustomerAccount($customer,$max_amount,$account_money,$account_type);
            $account_record_data['order_id'] = $order_id;
            $account_record_data['pay_cash'] = $account_record_data['pay_cash']>0?-$account_record_data['pay_cash']:0;//下单为负值
            $account_record_data['pay_scholarship'] = $account_record_data['pay_scholarship']>0?-$account_record_data['pay_scholarship']:0;
            $account_record_data['cash'] = $account_record_data['pay_cash']+$account_record_data['pay_pos']+$account_record_data['pay_card']+$account_record_data['pay_scholarship']+$account_record_data['deposit'];
            $account_record_data['note'] = '订单';
            \Yii::$app->db->createCommand()->insert('{{%account_record}}', $account_record_data)->execute();
        }elseif($account_type == 4){//保证金相关
            $deposit_money = isset($options['deposit_money'])?$options['deposit_money']:0;//暂时先只考虑交保证金吧
            $account_record_data['deposit'] = -$deposit_money;//交保证金是负数，退保证金为正的
            $account_record_data['cash'] = $account_record_data['pay_cash']+$account_record_data['pay_pos']+$account_record_data['pay_card']+$account_record_data['pay_scholarship']+$account_record_data['deposit'];
            $account_record_data['note'] = '支付保证金';
            \Yii::$app->db->createCommand()->insert('{{%account_record}}',  $account_record_data)->execute();
        }else{//其他情况
            $account_money['scholar_add_amount'] = $scholarship;
            $account_money['cash_add_amount'] = $cash;
            Account::changeCustomerAccount($customer,$max_amount,$account_money,$account_type);
            if($account_type == 1){
                $account_record_data['note'] = '充值';
            }elseif($account_type == 2){
                $account_record_data['note'] = '抢奖学金红包';
            }elseif($account_type == 3){
                $account_record_data['note'] = '转奖学金';
            }elseif($account_type == 7){//退课
                $order_id = isset($options['order_id'])?$options['order_id'] : 0;//订单独有的
                $account_record_data['order_id'] = $order_id;
                $account_record_data['note'] = '订单退课';
            }elseif($account_type == 8){
                $account_record_data['note'] = '交会费';
            }else{
                $account_record_data['note'] = '其他';
            }
            $account_record_data['pay_cash'] = isset($options['member_fee'])?-$options['member_fee']:0;
            $account_record_data['cash'] = $account_record_data['pay_cash']+$account_record_data['pay_pos']+$account_record_data['pay_card']+$account_record_data['pay_scholarship']+$account_record_data['deposit'];
            \Yii::$app->db->createCommand()->insert('{{%account_record}}',  $account_record_data)->execute();
        }
        return true;
    }

    /*
     * customer表相关字段资金的更改
     * customer: 用户
     * max_amount: 可用最大奖学金限制
     * add_amount: 要增加的奖学金金额    */
    public static function changeCustomerAccount($customer_arr, $max_amount, $account_money, $state,$spendscholarship=0){
        $add_sholar_amount = isset($account_money['scholar_add_amount'])?$account_money['scholar_add_amount']:0;
        $add_cash_amount = isset($account_money['cash_add_amount'])?$account_money['cash_add_amount']:0;
        $used_scholarship=AccountRecord::find()->where(['customer_id'=>$customer_arr['id']])->andWhere("state!=2 and state!=3 and state!=6")->sum('pay_scholarship');//已经使用的奖学金金额，非充值的类型
        $used_scholarship=$used_scholarship==null?0:$used_scholarship;
        $remain_amount=$max_amount+$used_scholarship-$customer_arr['scholarship_available'];//允许增加的奖学金金额
        if($state == 1){
            $schollarship_frozen_note = '充值';
        }elseif($state == 2){
            $schollarship_frozen_note = '抢奖学金红包';
        }elseif($state == 3){
            $schollarship_frozen_note = '转奖学金';
        }elseif($state == 6){
            $schollarship_frozen_note = '卡激活奖学金';
        }elseif($state == 7){
            $schollarship_frozen_note = '订单退课';
        }else{
            $schollarship_frozen_note = '其他';
        }

        $customer_branchaccount = CustomerBranchaccount::findOne(['customer_id'=>$customer_arr['id'],'mode'=>\Yii::$app->params['mode'],'site_id'=>Fun::getSiteId()]);
        if(empty($customer_branchaccount)){
            $customer_branchaccount = new CustomerBranchaccount();
            $customer_branchaccount->customer_id = $customer_arr['id'];
            $customer_branchaccount->mode = \Yii::$app->params['mode'];
            $customer_branchaccount->site_id = Fun::getSiteId();
            $customer_branchaccount->scholarship_available = 0;
            $customer_branchaccount->scholarship_frozen = 0;
            $customer_branchaccount->cash = 0;
            $customer_branchaccount->deposit = 0;
            $customer_branchaccount->is_default = 1;
            $customer_branchaccount->grade_id = 1;
            $customer_branchaccount->save(false);
        }
        if($state == 6){//开卡激活
            $customer_branchaccount->grade_id = 2;//更改为vip会员的状态
        }
        if(in_array($state,[0,1,2,3,6,7])){//充加钱 奖学金是加的 退课的情况也是加
            if($state == 7){ //退课的奖学金应该也是直接加到customer的scholarship_available中
                //退课的情况,现金
                if($add_cash_amount > 0){
                    $customer_branchaccount->cash += $add_cash_amount;//微信支付的钱退到账户里面
                }
                if($add_sholar_amount > 0){//退课的时候直接增加，要是按照remain_amount的话 就直接到冻结了，因为remain是0
                    $customer_branchaccount->scholarship_available += $add_sholar_amount;
                    $customer_branchaccount->save(false);
                }
            }else{
                if($remain_amount > 0){
                    if($remain_amount >= $add_sholar_amount){
                        $customer_branchaccount->scholarship_available += $add_sholar_amount;
                        $customer_branchaccount->save(false);
                    }else{
                        $customer_branchaccount->scholarship_available += $remain_amount;
                        $customer_branchaccount->scholarship_frozen+=$add_sholar_amount-$remain_amount;
                        $customer_branchaccount->save(false);
                        $frozen_log_1=new ScholarshipFrozenLog(['customer_id'=>$customer_arr['id'],'mode'=>\Yii::$app->params['mode'],'site_id'=>Fun::getSiteId(),'money'=>$add_sholar_amount-$remain_amount,'grab_time' =>time(),'invalid_time'=>time()+3600*24*7,'note'=>$schollarship_frozen_note]);
                        $frozen_log_1->save(false);
                    }
                }else{
                    $customer_branchaccount->scholarship_frozen+=$add_sholar_amount;
                    $customer_branchaccount->save(false);
                    $frozen_log_2=new ScholarshipFrozenLog(['customer_id'=>$customer_arr['id'],'mode'=>\Yii::$app->params['mode'],'site_id'=>Fun::getSiteId(),'money'=>$add_sholar_amount,'grab_time' =>time(),'invalid_time'=>time()+3600*24*7,'note'=>$schollarship_frozen_note]);
                    $frozen_log_2->save(false);
                }
            }
        }else{//奖学金为0or负值 减的 是订单 4,5是交保证金or订单支付
            if($state == 5){//订单类型 下单时候现金对customer没啥影响
                $customer_branchaccount->scholarship_available += $add_sholar_amount;//此时为加了个负值
                /*\Yii::error('account_money in account:');
                \Yii::error($account_money);*/
                if($account_money['deposit'] != 0){
                    $deposit_money = abs($account_money['deposit']);
                    if (!empty($customer_branchaccount->deposit) && $customer_branchaccount->deposit != 0) {
                        $customer_branchaccount->deposit = (float)$customer_branchaccount->deposit + (float)$deposit_money;
                    } else {
                        $customer_branchaccount->deposit = (float)$deposit_money;
                    }
                }
                $customer_branchaccount->save(false);
            }
        }
    }

}